iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 12
0
AI & Machine Learning

ChatBot&Chatbase系列 第 12

Day12[Line ChatBot]收發訊息

  • 分享至 

  • xImage
  •  

初步的先做一個可以收發訊息的bot
使用的python檔案為app.py
( 程式碼參考: https://github.com/LukeHong/line_bot_echo )
有稍微修改了一下
1.打開app.py,完整的程式碼如下

from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

app = Flask(__name__)


line_bot_api = LineBotApi('YOUR_LineBot_Channel access token')
handler = WebhookHandler('YOUR_LineBot_Channel secret')

@app.route("/", methods=['GET'])
def hello():
    return "Hello World!"

@app.route("/", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    print("Request body: " + body, "Signature: " + signature)
    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
       abort(400)

    return 'OK'


@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    msg = event.message.text
    print(msg)
    msg = msg.encode('utf-8')
    line_bot_api.reply_message(event.reply_token,TextSendMessage(text=event.message.text))

if __name__ == "__main__":
    app.run(debug=True,port=80)

以下兩步驟為說明

2.說明一下收發訊息的部分
這是收訊息的部分
https://ithelp.ithome.com.tw/upload/images/20171231/2010714402Vx4s5hOW.png
收到的訊息也可以在cmd中很清楚的看到整個訊息事件
https://ithelp.ithome.com.tw/upload/images/20171231/20107144Iq4sBDg7kJ.png

3.而發出的訊息,目前是收到什麼內容就回覆什麼
https://ithelp.ithome.com.tw/upload/images/20171231/20107144J6XVZFY93a.png

4.測試一下
https://ithelp.ithome.com.tw/upload/images/20171231/201071446APgWlq9o2.png


上一篇
Day11[Line ChatBot]設定webhook
下一篇
Day13[Line ChatBot]Line@ MANAGER內建功能
系列文
ChatBot&Chatbase30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言